package mspbots.teams.client.core.teams;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.teams.client.core.SyncRequest;
import mspbots.teams.client.oauth.TokenState;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.validation.Valid;

/**
 * TeamsController
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/8/28
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("data-teams/{tenantId}")
public class TeamsController {

    private final TeamsServiceImpl teamsServiceImpl;

    @InitBinder("syncRequest")
    public void initMerchantOnlyBinder(WebDataBinder binder) {
        binder.addValidators(new SyncRequest.SyncRequestValidator());
    }

    @GetMapping(path = "test")
    public Mono<JsonNode> test(@PathVariable Long tenantId) {
        return this.teamsServiceImpl.initialize(tenantId);
    }

    @GetMapping(path = "synchronise")
    public Mono<ObjectNode> synchronise(@PathVariable Long tenantId, @Valid SyncRequest syncRequest) {
        return this.teamsServiceImpl.synchronise(tenantId, syncRequest);
    }

    @DeleteMapping
    public Mono<Boolean> deleting(@PathVariable Long tenantId) {
        return this.teamsServiceImpl.deleting(tenantId);
    }

    @GetMapping("on-off/{onOff}")
    public Mono<Boolean> onOff(@PathVariable Long tenantId, @PathVariable String onOff) {
        return this.teamsServiceImpl.onOff(tenantId, onOff);
    }

    @GetMapping("exists/applications")
    public Flux<JsonNode> existsApplication(@PathVariable Long tenantId) {
        return this.teamsServiceImpl.existsApplication(TokenState.withDefault(tenantId));
    }

    @GetMapping("login-sync")
    public Mono<String> loginSync(@PathVariable Long tenantId, String accessToken) {
        return this.teamsServiceImpl.loginSync(TokenState.withDefault(tenantId).setAccessToken(accessToken)
                .setTokenType(TokenState.TokenType.loginToken));
    }

}
